import { useCallback, useEffect, useState } from 'react';

import styles from './index.module.less';

interface CusTabProps {
  onClick?: (key: string) => void;
  option: CusOptionItem[];
  defaultValue?: string;
}

export interface CusOptionItem {
  key: string;
  value: string;
}

export default ({ onClick, option, defaultValue }: CusTabProps) => {
  const [selected, setSelected] = useState<any>('');

  useEffect(() => {
    setSelected(defaultValue);
  }, [defaultValue]);

  // 点击tab项的时候触发
  const handleClick = useCallback((optionItem: CusOptionItem) => {
    setSelected(optionItem.value);
    onClick?.(optionItem.value);
  }, []);

  return (
    <div className={styles.box}>
      {option.map((item: CusOptionItem) => (
        <div
          key={item.key}
          className={`${styles.item} ${selected === item.value && styles.selected}`}
          onClick={() => handleClick(item)}
        >
          {item.key}
        </div>
      ))}
    </div>
  );
};
